#!/usr/bin/python3
"""
OpenCloudOS 9 AI软件验证工具 - 交互式启动器
"""

import os
import sys
import json
import subprocess
from pathlib import Path
from datetime import datetime


class InteractiveValidator:
    """交互式验证器"""
    
    def __init__(self):
        self.log_dir = Path("validation_logs")
        self.success_dir = Path("validation_logs/success")
        self.failure_dir = Path("validation_logs/failure")
        self.setup_directories()
    
    def setup_directories(self):
        """创建必要的目录"""
        self.log_dir.mkdir(exist_ok=True)
        self.success_dir.mkdir(exist_ok=True)
        self.failure_dir.mkdir(exist_ok=True)
    
    def clear_screen(self):
        """清屏"""
        os.system('clear' if os.name == 'posix' else 'cls')
    
    def print_header(self):
        """打印头部信息"""
        self.clear_screen()
        print("=" * 60)
        print("🤖 OpenCloudOS 9 AI软件包验证工具 - 交互式启动器")
        print("=" * 60)
        print(f"当前时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"工作目录: {Path.cwd()}")
        print()
    
    def check_environment(self):
        """检查环境"""
        self.print_header()
        print("🔍 正在检测系统环境...")
        
        # 检查Python版本
        print(f"  Python版本: {sys.version}")
        
        # 检查必要文件
        required_files = [
            "ai_package_validator.py",
            "advanced_cli.py",
            "validate_cli.py",
            "system_check.py"
        ]
        
        missing_files = []
        for file in required_files:
            if not Path(file).exists():
                missing_files.append(file)
        
        if missing_files:
            print(f"  ❌ 缺少必要文件: {', '.join(missing_files)}")
            return False
        
        print("  ✅ 所有必需文件存在")
        
        # 检查依赖
        try:
            import psutil
            print(f"  ✅ psutil版本: {psutil.__version__}")
        except ImportError:
            print("  ⚠️  psutil未安装，部分功能可能受限")
        
        print("\n✅ 环境检测完成！")
        input("\n按回车键继续...")
        return True
    
    def show_main_menu(self):
        """显示主菜单"""
        while True:
            self.print_header()
            print("📋 主菜单")
            print("-" * 30)
            print("1. 系统环境检测")
            print("2. 快速工具测试")
            print("3. 查看可用配置文件")
            print("4. 批量验证软件包")
            print("5. 查看验证结果")
            print("6. 查询软件包日志")
            print("7. 生成验证报告")
            print("0. 退出程序")
            print()
            
            choice = input("请选择操作 (0-7): ").strip()
            
            if choice == "1":
                self.run_system_check()
            elif choice == "2":
                self.run_quick_test()
            elif choice == "3":
                self.show_config_files()
            elif choice == "4":
                self.run_batch_validation()
            elif choice == "5":
                self.show_validation_results()
            elif choice == "6":
                self.query_package_log()
            elif choice == "7":
                self.generate_report()
            elif choice == "0":
                print("\n👋 感谢使用OpenCloudOS 9 AI软件验证工具！")
                sys.exit(0)
            else:
                print("\n❌ 无效选择，请重新输入")
                input("按回车键继续...")
    
    def run_system_check(self):
        """运行系统检测"""
        self.print_header()
        print("🖥️  系统环境检测")
        print("-" * 30)
        
        if not Path("system_check.py").exists():
            print("❌ system_check.py 文件不存在")
            input("按回车键返回主菜单...")
            return
        
        try:
            result = subprocess.run(
                ["python3", "system_check.py"],
                capture_output=True,
                text=True,
                timeout=120
            )
            
            if result.returncode == 0:
                print("✅ 系统检测完成")
            else:
                print("⚠️  系统检测完成但有警告")
                if result.stdout:
                    print("输出:")
                    print(result.stdout)
                if result.stderr:
                    print("错误:")
                    print(result.stderr)
        except subprocess.TimeoutExpired:
            print("❌ 系统检测超时")
        except Exception as e:
            print(f"❌ 系统检测异常: {e}")
        
        input("按回车键返回主菜单...")
    
    def run_quick_test(self):
        """运行快速测试"""
        self.print_header()
        print("⚡ 快速工具测试")
        print("-" * 30)
        
        if not Path("quick_test.py").exists():
            print("❌ quick_test.py 文件不存在")
            input("按回车键返回主菜单...")
            return
        
        try:
            result = subprocess.run(
                ["python3", "quick_test.py"],
                capture_output=True,
                text=True,
                timeout=120
            )
            
            if result.returncode == 0:
                print("✅ 快速测试完成")
                if result.stdout:
                    print("输出:")
                    print(result.stdout)
            else:
                print("❌ 快速测试失败")
                if result.stderr:
                    print("错误:")
                    print(result.stderr)
        except subprocess.TimeoutExpired:
            print("❌ 快速测试超时")
        except Exception as e:
            print(f"❌ 快速测试异常: {e}")
        
        input("按回车键返回主菜单...")
    
    def show_config_files(self):
        """显示可用配置文件"""
        self.print_header()
        print("📂 可用配置文件")
        print("-" * 30)
        
        config_files = list(Path(".").glob("*config*.json"))
        
        if not config_files:
            print("❌ 未找到配置文件")
            input("按回车键返回主菜单...")
            return
        
        for i, config_file in enumerate(config_files, 1):
            # 获取文件信息
            stat = config_file.stat()
            size = stat.st_size
            mtime = datetime.fromtimestamp(stat.st_mtime)
            
            print(f"{i}. {config_file.name}")
            print(f"   大小: {size} 字节")
            print(f"   修改时间: {mtime.strftime('%Y-%m-%d %H:%M:%S')}")
            print()
        
        input("按回车键返回主菜单...")
    
    def run_batch_validation(self):
        """运行批量验证"""
        self.print_header()
        print("📦 批量验证软件包")
        print("-" * 30)
        
        # 查找配置文件
        config_files = list(Path(".").glob("*config*.json"))
        
        if not config_files:
            print("❌ 未找到配置文件")
            input("按回车键返回主菜单...")
            return
        
        print("可用配置文件:")
        for i, config_file in enumerate(config_files, 1):
            print(f"{i}. {config_file.name}")
        
        print("0. 返回主菜单")
        print()
        
        try:
            choice = input("请选择配置文件 (0-{}): ".format(len(config_files))).strip()
            
            if choice == "0":
                return
            
            choice_idx = int(choice) - 1
            if 0 <= choice_idx < len(config_files):
                config_file = config_files[choice_idx]
                print(f"\n正在使用 {config_file.name} 进行验证...")
                
                # 运行验证
                cmd = ["python3", "advanced_cli.py", "batch", str(config_file)]
                print(f"执行命令: {' '.join(cmd)}")
                
                result = subprocess.run(cmd, capture_output=True, text=True, timeout=3600)  # 1小时超时
                
                if result.returncode == 0:
                    print("✅ 批量验证完成")
                    # 整理日志文件
                    self.organize_logs()
                else:
                    print("❌ 批量验证失败")
                    if result.stderr:
                        print("错误:")
                        print(result.stderr)
                
                print("\n日志文件已整理到 success/ 和 failure/ 目录中")
            else:
                print("❌ 无效选择")
        except (ValueError, IndexError):
            print("❌ 无效输入")
        except subprocess.TimeoutExpired:
            print("❌ 验证超时")
        except Exception as e:
            print(f"❌ 验证异常: {e}")
        
        input("按回车键返回主菜单...")
    
    def organize_logs(self):
        """整理日志文件"""
        # 查找最新的批量验证日志
        batch_logs = list(self.log_dir.glob("batch_validation_*.json"))
        if not batch_logs:
            return
        
        latest_log = max(batch_logs, key=lambda x: x.stat().st_mtime)
        
        try:
            with open(latest_log, 'r', encoding='utf-8') as f:
                batch_result = json.load(f)
            
            # 根据验证结果移动日志文件
            for pkg_result in batch_result.get('packages_results', []):
                pkg_name = pkg_result.get('package', 'unknown')
                
                # 查找对应的单包日志文件
                pkg_logs = list(self.log_dir.glob(f"{pkg_name}_*.json"))
                if not pkg_logs:
                    continue
                
                latest_pkg_log = max(pkg_logs, key=lambda x: x.stat().st_mtime)
                
                # 根据验证结果移动文件
                if pkg_result.get('overall_success', False):
                    # 移动到成功目录
                    target_path = self.success_dir / latest_pkg_log.name
                    if not target_path.exists():
                        latest_pkg_log.rename(target_path)
                else:
                    # 移动到失败目录
                    target_path = self.failure_dir / latest_pkg_log.name
                    if not target_path.exists():
                        latest_pkg_log.rename(target_path)
                        
        except Exception as e:
            print(f"整理日志文件时出错: {e}")
    
    def show_validation_results(self):
        """显示验证结果"""
        self.print_header()
        print("📊 验证结果概览")
        print("-" * 30)
        
        # 查找最新的批量验证日志
        batch_logs = list(self.log_dir.glob("batch_validation_*.json"))
        if not batch_logs:
            print("❌ 未找到批量验证日志")
            input("按回车键返回主菜单...")
            return
        
        latest_log = max(batch_logs, key=lambda x: x.stat().st_mtime)
        
        try:
            with open(latest_log, 'r', encoding='utf-8') as f:
                batch_result = json.load(f)
            
            # 显示汇总信息
            total = batch_result.get('total_packages', 0)
            success = batch_result.get('successful_packages', 0)
            failed = batch_result.get('failed_packages', 0)
            success_rate = batch_result.get('summary', {}).get('success_rate', 0)
            
            print(f"验证时间: {batch_result.get('batch_timestamp', 'Unknown')}")
            print(f"总包数: {total}")
            print(f"成功: {success}")
            print(f"失败: {failed}")
            print(f"成功率: {success_rate:.1f}%")
            
            # 显示成功和失败的包
            successful_packages = []
            failed_packages = []
            
            for result in batch_result.get('packages_results', []):
                package_name = result.get('package', 'Unknown')
                if result.get('overall_success', False):
                    successful_packages.append(package_name)
                else:
                    failed_packages.append(package_name)
            
            if successful_packages:
                print(f"\n✅ 成功的包 ({len(successful_packages)}):")
                for i, pkg in enumerate(successful_packages, 1):
                    print(f"  {i:2d}. {pkg}")
            
            if failed_packages:
                print(f"\n❌ 失败的包 ({len(failed_packages)}):")
                for i, pkg in enumerate(failed_packages, 1):
                    print(f"  {i:2d}. {pkg}")
            
            # 显示日志目录结构
            print(f"\n📂 日志目录结构:")
            success_count = len(list(self.success_dir.glob("*.json")))
            failure_count = len(list(self.failure_dir.glob("*.json")))
            print(f"  成功日志: {success_count} 个文件")
            print(f"  失败日志: {failure_count} 个文件")
            
        except Exception as e:
            print(f"❌ 读取验证结果时出错: {e}")
        
        input("按回车键返回主菜单...")
    
    def query_package_log(self):
        """查询软件包日志"""
        self.print_header()
        print("🔍 查询软件包日志")
        print("-" * 30)
        
        # 获取所有日志文件
        log_files = []
        for dir_path in [self.log_dir, self.success_dir, self.failure_dir]:
            log_files.extend(dir_path.glob("*.json"))
        
        if not log_files:
            print("❌ 未找到日志文件")
            input("按回车键返回主菜单...")
            return
        
        # 按包名分组
        package_logs = {}
        for log_file in log_files:
            # 提取包名（假设文件名格式为 package_timestamp.json）
            parts = log_file.stem.split('_')
            if len(parts) >= 2:
                pkg_name = '_'.join(parts[:-1])  # 处理包名中可能包含下划线的情况
                if pkg_name not in package_logs:
                    package_logs[pkg_name] = []
                package_logs[pkg_name].append(log_file)
        
        if not package_logs:
            print("❌ 未找到有效的软件包日志")
            input("按回车键返回主菜单...")
            return
        
        # 显示包列表
        packages = list(package_logs.keys())
        print("可用的软件包:")
        for i, pkg in enumerate(packages, 1):
            log_count = len(package_logs[pkg])
            status = "✅" if (self.success_dir / f"{pkg}_*.json").exists() else "❌"
            print(f"{i:2d}. {status} {pkg} ({log_count} 个日志文件)")
        
        print("0. 返回主菜单")
        print()
        
        try:
            choice = input("请选择要查看的软件包 (0-{}): ".format(len(packages))).strip()
            
            if choice == "0":
                return
            
            choice_idx = int(choice) - 1
            if 0 <= choice_idx < len(packages):
                pkg_name = packages[choice_idx]
                pkg_logs = package_logs[pkg_name]
                
                print(f"\n{pkg_name} 的日志文件:")
                for i, log_file in enumerate(pkg_logs, 1):
                    stat = log_file.stat()
                    size = stat.st_size
                    mtime = datetime.fromtimestamp(stat.st_mtime)
                    print(f"{i}. {log_file.name}")
                    print(f"   大小: {size} 字节")
                    print(f"   修改时间: {mtime.strftime('%Y-%m-%d %H:%M:%S')}")
                
                # 选择查看哪个日志
                if len(pkg_logs) > 1:
                    log_choice = input(f"\n请选择要查看的日志文件 (1-{len(pkg_logs)}, 0返回): ").strip()
                    if log_choice == "0":
                        return
                    try:
                        log_idx = int(log_choice) - 1
                        if 0 <= log_idx < len(pkg_logs):
                            selected_log = pkg_logs[log_idx]
                        else:
                            print("❌ 无效选择")
                            input("按回车键返回主菜单...")
                            return
                    except ValueError:
                        print("❌ 无效输入")
                        input("按回车键返回主菜单...")
                        return
                else:
                    selected_log = pkg_logs[0]
                
                # 显示日志内容
                print(f"\n📄 {selected_log.name} 的内容:")
                print("-" * 50)
                try:
                    with open(selected_log, 'r', encoding='utf-8') as f:
                        content = json.load(f)
                        print(json.dumps(content, ensure_ascii=False, indent=2))
                except Exception as e:
                    print(f"❌ 读取日志文件时出错: {e}")
            else:
                print("❌ 无效选择")
        except (ValueError, IndexError):
            print("❌ 无效输入")
        except Exception as e:
            print(f"❌ 查询日志时出错: {e}")
        
        input("按回车键返回主菜单...")
    
    def generate_report(self):
        """生成验证报告"""
        self.print_header()
        print("📈 生成验证报告")
        print("-" * 30)
        
        print("请选择报告格式:")
        print("1. 文本报告")
        print("2. HTML报告")
        print("0. 返回主菜单")
        print()
        
        choice = input("请选择 (0-2): ").strip()
        
        if choice == "0":
            return
        elif choice in ["1", "2"]:
            try:
                if choice == "1":
                    cmd = ["python3", "advanced_cli.py", "report"]
                    print("正在生成文本报告...")
                else:
                    cmd = ["python3", "advanced_cli.py", "report", "--format", "html"]
                    print("正在生成HTML报告...")
                
                result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
                
                if result.returncode == 0:
                    print("✅ 报告生成完成")
                    if result.stdout:
                        print(result.stdout)
                else:
                    print("❌ 报告生成失败")
                    if result.stderr:
                        print("错误:")
                        print(result.stderr)
            except subprocess.TimeoutExpired:
                print("❌ 报告生成超时")
            except Exception as e:
                print(f"❌ 报告生成异常: {e}")
        else:
            print("❌ 无效选择")
        
        input("按回车键返回主菜单...")
    
    def run(self):
        """运行交互式验证器"""
        # 首先检查环境
        if not self.check_environment():
            print("❌ 环境检查失败，无法继续")
            sys.exit(1)
        
        # 显示主菜单
        self.show_main_menu()


def main():
    """主函数"""
    validator = InteractiveValidator()
    validator.run()


if __name__ == "__main__":
    main()